﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Works;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 工作站管理接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WorkstationController : ControllerBase
    {
        public WorkstationController(IWorkstationServices services ,LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IWorkstationServices Services { get; }
        public LogHelper LogHelper { get; }


        /// <summary>
        /// 获取所有工作站管理数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task< IActionResult> GetAll()
        {
            var status=BaseStatus.CreateInstance();

            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";


                //写日志
                await LogHelper.WriteErrorLog("工作站管理-获取所有", ex, HttpContext);
            }
            return Ok(status);

        }
        /// <summary>
        /// 分页获取工作站管理数据
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="WorkstationCode">工作站编码</param>
        /// <param name="WorkstationName">工作站名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery]string WorkstationCode, [FromQuery] string WorkstationName, [FromQuery] string WorkshopId, [FromQuery] string ProcessId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                WorkstationCode = WorkstationCode ?? "";
                WorkstationName = WorkstationName ?? "";
                WorkshopId = WorkshopId ?? "";
                ProcessId = ProcessId ?? "";

                var list = await Services.GetAsync(PageIndex,PageSize, WorkstationCode, WorkstationName, WorkshopId, ProcessId);
                status.Data = list;
                status.Count = await Services.GetCountAsync(WorkstationCode, WorkstationName, WorkshopId, ProcessId);

            }
            catch (Exception ex)
            {

                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("工作站管理-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据工作站Id获取设备资源
        /// </summary>
        /// <param name="WorkstationId"></param>
        /// <returns></returns>
        [HttpGet("GetWorkstationbyId")]
        public async Task<IActionResult> GetWorkstationbyId([FromQuery] string WorkstationId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetWorkstationbyIdAsync(WorkstationId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站-获取设备资源", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 新增工作站管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] Workstation model, [FromForm] string WorkstationMachineString)
        {
            var status = BaseStatus.CreateInstance();
            List<WorkstationMachine> list = new List<WorkstationMachine>();
            try
            {
                if (!string.IsNullOrEmpty(WorkstationMachineString))
                {
                    list = JsonConvert.DeserializeObject<List<WorkstationMachine>>(WorkstationMachineString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime=StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess= await Services.AddAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception  ex)
            {

                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站管理-新增", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 修改工作站管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] Workstation model,[FromForm] string WorkstationMachineString)
        {
            var status = BaseStatus.CreateInstance();
            List<WorkstationMachine> list = new List<WorkstationMachine>();
            try
            {
                if (!string.IsNullOrEmpty(WorkstationMachineString))
                {
                    list = JsonConvert.DeserializeObject<List<WorkstationMachine>>(WorkstationMachineString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站管理-修改", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 批量删除工作站管理
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess) 
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站管理-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 删除工作站管理数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {


                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站管理-批量删除", ex, HttpContext);
            }
            return Ok(status);

        }


        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="工作站编码",Fileld="WorkstationCode"},
                    new ReportDomain{ Title="工作站名称",Fileld="WorkstationName"},
                    new ReportDomain{ Title="工作站地点",Fileld="WorkstationAddress"},
                    new ReportDomain{ Title="所在车间名称",Fileld="WorkshopName"},
                    new ReportDomain{ Title="工序名称",Fileld="ProcessName"},
                    new ReportDomain{ Title="最后修改",Fileld="LastUpdateTime"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},

                };
                var fileArray = BaseReport.Export(list, "工作站信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "工作站信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("工作站信息-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }





    }
}
